"""
扫描记录管理器
"""
from typing import List, Dict, Any, Optional
from datetime import datetime
from sqlalchemy import desc, and_, func
from com.db.models import ScanRecord
from com.db.sqlalchemy_database import SQLAlchemyDatabaseManager

class ScanRecordManager:
    def __init__(self):
        """
        初始化扫描记录管理器
        """
        self.db = SQLAlchemyDatabaseManager()
    
    def add_scan_record(self, record_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        """
        添加扫描记录
        :param record_data: 记录数据
        :return: 添加的记录
        """
        # 转换时间戳为datetime
        for field in ['thread_create_time', 'wait_start_time', 'wait_end_time', 
                     'scan_start_time', 'scan_end_time', 'thread_end_time']:
            if field in record_data:
                record_data[field] = datetime.fromtimestamp(record_data[field])
        
        record = ScanRecord(**record_data)
        self.db.add(record)
        return self._convert_model_to_dict(record) if record else None
    
    def get_record_by_id(self, record_id: int) -> Optional[Dict[str, Any]]:
        """
        根据ID获取扫描记录
        :param record_id: 记录ID
        :return: 记录信息字典或None
        """
        record = self.db.get_by_id(ScanRecord, record_id)
        return self._convert_model_to_dict(record) if record else None
    
    def get_records_by_task_id(self, task_id: int) -> List[Dict[str, Any]]:
        """
        获取指定任务的所有扫描记录
        :param task_id: 任务ID
        :return: 记录列表
        """
        session, query = self.db.query_with_session(ScanRecord)
        try:
            records = query.filter(ScanRecord.task_id == task_id).all()
            return [self._convert_model_to_dict(record) for record in records]
        finally:
            session.close()
    
    def get_records_by_goods_id(self, goods_id: str, start_time: Optional[datetime] = None) -> List[Dict[str, Any]]:
        """
        获取指定商品的所有扫描记录
        :param goods_id: 商品ID
        :param start_time: 开始时间
        :return: 记录列表
        """
        session, query = self.db.query_with_session(ScanRecord)
        try:
            filters = [ScanRecord.goods_id == goods_id]
            if start_time:
                filters.append(ScanRecord.create_at >= start_time)
                
            records = query.filter(and_(*filters))\
                .order_by(desc(ScanRecord.create_at))\
                .all()
            return [self._convert_model_to_dict(record) for record in records]
        finally:
            session.close()
    
    def get_records_by_account_id(self, account_id: int) -> List[Dict[str, Any]]:
        """
        获取指定账号的所有扫描记录
        :param account_id: 账号ID
        :return: 记录列表
        """
        session, query = self.db.query_with_session(ScanRecord)
        try:
            records = query.filter(ScanRecord.account_id == account_id).all()
            return [self._convert_model_to_dict(record) for record in records]
        finally:
            session.close()
    
    def get_records_by_status(self, status: str, start_time: Optional[datetime] = None, 
                            end_time: Optional[datetime] = None) -> List[Dict[str, Any]]:
        """
        根据状态获取扫描记录
        :param status: 扫描状态(success/failed/limited)
        :param start_time: 开始时间
        :param end_time: 结束时间
        :return: 记录列表
        """
        session, query = self.db.query_with_session(ScanRecord)
        try:
            filters = [ScanRecord.scan_status == status]
            if start_time:
                filters.append(ScanRecord.create_at >= start_time)
            if end_time:
                filters.append(ScanRecord.create_at <= end_time)
                
            records = query.filter(and_(*filters)).all()
            return [self._convert_model_to_dict(record) for record in records]
        finally:
            session.close()
    
    def get_recent_records(self, limit: int = 100, offset: int = 0) -> List[Dict[str, Any]]:
        """
        获取最近的扫描记录
        :param limit: 限制数量
        :param offset: 偏移量
        :return: 记录列表
        """
        session, query = self.db.query_with_session(ScanRecord)
        try:
            records = query.order_by(desc(ScanRecord.create_at))\
                .limit(limit)\
                .offset(offset)\
                .all()
            return [self._convert_model_to_dict(record) for record in records]
        finally:
            session.close()
    
    def get_statistics(self, start_time: Optional[datetime] = None, 
                      end_time: Optional[datetime] = None) -> Dict[str, Any]:
        """
        获取扫描统计信息
        :param start_time: 开始时间
        :param end_time: 结束时间
        :return: 统计信息
        """
        session, query = self.db.query_with_session(ScanRecord)
        try:
            filters = []
            if start_time:
                filters.append(ScanRecord.create_at >= start_time)
            if end_time:
                filters.append(ScanRecord.create_at <= end_time)
            
            base_query = query.filter(and_(*filters))
            
            # 基本统计
            total_scans = base_query.count()
            success_scans = base_query.filter(ScanRecord.scan_status == 'success').count()
            failed_scans = base_query.filter(ScanRecord.scan_status == 'failed').count()
            limited_scans = base_query.filter(ScanRecord.scan_status == 'limited').count()
            
            # 时间统计（平均值，单位：毫秒）
            time_stats = base_query.filter(ScanRecord.scan_status == 'success')\
                .with_entities(
                    func.avg(ScanRecord.wait_duration).label('avg_wait'),
                    func.avg(ScanRecord.scan_duration).label('avg_scan'),
                    func.avg(ScanRecord.api_response_time).label('avg_api'),
                    func.avg(ScanRecord.total_duration).label('avg_total')
                ).first()
            
            return {
                'total_scans': total_scans,
                'success_scans': success_scans,
                'failed_scans': failed_scans,
                'limited_scans': limited_scans,
                'success_rate': (success_scans / total_scans * 100) if total_scans > 0 else 0,
                'time_statistics': {
                    'average_wait_time': float(time_stats.avg_wait or 0),
                    'average_scan_time': float(time_stats.avg_scan or 0),
                    'average_api_time': float(time_stats.avg_api or 0),
                    'average_total_time': float(time_stats.avg_total or 0)
                }
            }
        finally:
            session.close()
    
    def get_scan_stats(self, goods_id: int) -> Dict[str, Any]:
        """
        获取商品的扫描统计信息
        :param goods_id: 商品ID
        :return: 统计信息字典
        """
        session, query = self.db.query_with_session(ScanRecord)
        try:
            base_query = query.filter(ScanRecord.goods_id == goods_id)
            
            # 基本统计
            total_count = base_query.count()
            success_count = base_query.filter(ScanRecord.scan_status == 'success').count()
            
            return {
                'total_count': total_count,
                'success_count': success_count,
                'success_rate': (success_count / total_count * 100) if total_count > 0 else 0
            }
        finally:
            session.close()
    
    def _convert_model_to_dict(self, record: ScanRecord) -> Dict[str, Any]:
        """
        将模型对象转换为字典
        :param record: 记录对象
        :return: 字典
        """
        if not record:
            return None
            
        return {
            'id': record.id,
            'task_id': record.task_id,
            'script_id': record.script_id,
            'goods_id': record.goods_id,
            'goods_name': record.goods_name,
            'account_id': record.account_id,
            
            # 时间信息
            'thread_id': record.thread_id,
            'thread_create_time': record.thread_create_time,
            'wait_start_time': record.wait_start_time,
            'wait_end_time': record.wait_end_time,
            'wait_duration': record.wait_duration,
            'scan_start_time': record.scan_start_time,
            'scan_end_time': record.scan_end_time,
            'scan_duration': record.scan_duration,
            'thread_end_time': record.thread_end_time,
            'total_duration': record.total_duration,
            
            # 扫描配置
            'price_limit': record.price_limit,
            'min_paintwear': record.min_paintwear,
            'max_paintwear': record.max_paintwear,
            'remaining_purchase': record.remaining_purchase,
            
            # 扫描结果
            'api_response_code': record.api_response_code,
            'api_response_time': record.api_response_time,
            'found_items': record.found_items,
            'min_price': record.min_price,
            'max_price': record.max_price,
            'avg_price': record.avg_price,
            'scan_status': record.scan_status,
            'error_message': record.error_message,
            'selling_count': record.selling_count,
            'price_list': record.price_list,
            'purchase_success_count': record.purchase_success_count,
            
            # 额外信息
            'extra_data': record.extra_data,
            'create_at': record.create_at,
            'update_at': record.update_at
        }
